import { getUserInfo } from "@/Util";
import eventBus from "@/Util/EventBus";
import axios from "axios";
import { ChatInfo, ChatMsgInfo } from '@/Util/Constant'

class ChatModel {
    private msgList: Map<string, ChatMsgInfo[]> = new Map()
    public chatList: ChatInfo[] = [];
    public username: string;
    private currentChatfriend: string = '';
    constructor() {
        this.username = getUserInfo().username
        eventBus.on('updateName', this.setUsername)
    }
    getChatList() {
        return JSON.parse(JSON.stringify(this.chatList));
    }
    setCurrentChatfriend(name: string) {
        if (this.currentChatfriend !== name) {
            this.currentChatfriend = name;
            eventBus.emit('updateCurrentFriend')
            eventBus.emit('updateMsgList')
            eventBus.emit('updateScroller', true)
        }
    }
    getCurrentChatfriend(nickname?: boolean): string {
        if (nickname) {
            return this.chatList.find((item) => item.name == this.currentChatfriend)?.nickname || ''
        }
        return this.currentChatfriend
    }
    async getChatMsg(isGroup?: boolean) { //当一对一聊天的时候，chatId是对方的username
        let chatId = this.currentChatfriend;
        let msg = this.msgList.get(chatId)
        if (msg) {
            return JSON.parse(JSON.stringify(msg));
        }
        this.msgList.set(chatId, [])
        const token = localStorage.getItem('token')
        let { data } = await axios.get('/chat/chatMsg', {
            headers: { token },
            params: {
                chatId,
                isGroup
            }
        })
        if (data?.data) {
            let messages = data.data.messages
            messages.forEach((item: ChatMsgInfo) => {
                this.msgList.get(chatId)?.push({
                    sender: item.sender,
                    content: item.content,
                    createdAt: item.createdAt,
                    contentType: item.contentType,
                })
            });
        }
        return JSON.parse(JSON.stringify(this.msgList.get(chatId)))
    }
    async addChatMsgForModel(msg: ChatMsgInfo, isGroup?: boolean) {
        // 1.上传服务器
        let chatId = this.currentChatfriend;
        const token = localStorage.getItem('token')
        let { data } = await axios.post('/chat/chatMsg', {
            chatId: chatId,
            isGroup,
            msg
        }, {
            headers: { token }
        })
        // 2.本地缓存, 到这一步其实本地肯定已经缓存过了
        let msglist = this.msgList.get(chatId)
        msglist?.push(msg)
    }
    addChatMsg(msg: ChatMsgInfo, isGroup?: boolean) {
        let { content, sender, createdAt } = msg
        let msglist = this.msgList.get(sender)
        if (msglist) {
            msglist?.push(msg)
        } else {
            this.msgList.set(sender, [msg])
        }
        eventBus.emit('updateMsgList')
    }
    setUsername = (name: string) => {
        this.username = name;
    }
    getServerChatId(chatId: string, isGroup?: boolean) {
        if (isGroup) {
            return chatId
        }
        return this.username + chatId
    }
    addChatList(data: ChatInfo) {
        let item = this.chatList.find((item) => item.name == data.name)
        if (!item) {
            this.chatList.push(data)
            eventBus.emit('updateChatList') // 更新监听chatlist的位置
        }
    }
}
let chatModel = new ChatModel()
export default chatModel